#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
拦截配置API路由
"""

import logging
import json
from datetime import datetime
from bson import ObjectId
from flask import Blueprint, request, jsonify
from db.mongo import get_db
from intercept.services.manager import set_intercept_rules, get_intercept_status, clear_intercept_rules, get_response_for_request, should_intercept, record_interception

# 自定义JSON编码器，处理MongoDB的ObjectId
class JSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, ObjectId):
            return str(obj)
        if isinstance(obj, datetime):
            return obj.isoformat()
        return json.JSONEncoder.default(self, obj)

logger = logging.getLogger(__name__)
intercept_bp = Blueprint('intercept', __name__)

@intercept_bp.route('/rules', methods=['POST'])
def configure_interception():
    """配置拦截规则"""
    data = request.json

    if not data or 'session_id' not in data or 'rules' not in data:
        return jsonify({'error': 'Missing required parameters'}), 400

    session_id = data['session_id']
    rules = data['rules']

    try:
        # 检查会话是否存在
        db = get_db()
        session = db.sessions.find_one({'session_id': session_id})
        if not session:
            return jsonify({'error': 'Session not found'}), 404

        # 设置拦截规则
        result = set_intercept_rules(session_id, rules)

        return jsonify(result), 200
    except Exception as e:
        logger.error(f"配置拦截规则失败: {e}")
        return jsonify({'error': str(e)}), 500

@intercept_bp.route('/status/<session_id>', methods=['GET'])
def get_interception_status(session_id):
    """获取拦截状态"""
    try:
        # 检查会话是否存在
        db = get_db()
        session = db.sessions.find_one({'session_id': session_id})
        if not session:
            return jsonify({'error': 'Session not found'}), 404

        # 获取拦截状态
        status = get_intercept_status(session_id)

        return jsonify(status), 200
    except Exception as e:
        logger.error(f"获取拦截状态失败: {e}")
        return jsonify({'error': str(e)}), 500

@intercept_bp.route('/rules/<session_id>', methods=['DELETE'])
def clear_interception(session_id):
    """清除拦截规则"""
    try:
        # 检查会话是否存在
        db = get_db()
        session = db.sessions.find_one({'session_id': session_id})
        if not session:
            return jsonify({'error': 'Session not found'}), 404

        # 清除拦截规则
        result = clear_intercept_rules(session_id)

        return jsonify(result), 200
    except Exception as e:
        logger.error(f"清除拦截规则失败: {e}")
        return jsonify({'error': str(e)}), 500

@intercept_bp.route('/response', methods=['GET'])
def get_intercepted_response():
    """获取拦截的响应"""
    session_id = request.args.get('session_id')
    service_name = request.args.get('service_name')
    method = request.args.get('method')
    url = request.args.get('url')

    if not session_id or not service_name or not method or not url:
        return jsonify({'error': 'Missing required parameters'}), 400

    try:
        # 检查会话是否存在
        db = get_db()
        session = db.sessions.find_one({'session_id': session_id})
        if not session:
            return jsonify({'error': 'Session not found'}), 404

        # 检查是否应该拦截
        if not should_intercept(session_id, service_name, url):
            return jsonify({'error': 'No interception rule matches this request'}), 404

        # 获取响应
        response = get_response_for_request(session_id, service_name, method, url)

        if not response:
            return jsonify({'error': 'No matching response found'}), 404

        # 记录拦截事件
        record_interception(session_id, service_name)

        return json.dumps(response, cls=JSONEncoder), 200, {'Content-Type': 'application/json'}
    except Exception as e:
        logger.error(f"获取拦截响应失败: {e}")
        return jsonify({'error': str(e)}), 500
